<?php
namespace App\Http\Controllers\Admin;

use App\Models\ArticleCategoryModel;
use App\Validates\Admin\ArticleValidate;

class ArticleCategoryController extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if(request()->ajax()){
            $list = ArticleCategoryModel::listAll();
            return response()->json(ArticleCategoryModel::generateTree($list));
        }
        return view('admin/article/category/index');
    }

    /**
     * 显示创建资源表单页.
     */
    public function create()
    {
        $id = request()->input('id');
        if($id){
            $res = ArticleCategoryModel::find($id);
            $res['picture'] = $res['picture'] ? explode(";",$res['picture']) : "";
        }
        $tree = ArticleCategoryModel::treeList();
        return view('admin/article/category/modify',['model'=>$res,'tree'=>$tree]);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit()
    {
        if(request()->ajax()){
            $data = request()->post();

            $ArticleValidate = new ArticleValidate();
            if (!$ArticleValidate->scene('category')->check($data)) {
                return $this->result('', 500, $ArticleValidate->getError());
            }

            if($data['picture']){
                $data['picture'] = implode(";",$data['picture']);
            }
            $res = ArticleCategoryModel::editArticleCategory($data);
            return $this->result('', $res['code'], $res['msg']);
        }
    }

    /**
     * 删除指定资源
     * @param  int  $id
     */
    public function delete()
    {
        try {
            $ids = request()->input("id");
            $check = ArticleCategoryModel::where("pid",$ids)->first();
            if($check){
                return $this->result('',500,'请删除该分类子菜单');
            }
            $res = ArticleCategoryModel::destroy($ids);
            if($res) {
                return $this->result("", 200, "操作成功");
            }
            return $this->result("", 500, "操作失败");
        } catch (\Exception $e) {
            return $this->result('',500,$e->getMessage());
        }
    }
}
